package com.ruoyi.project.service.impl;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import com.ruoyi.common.core.exception.ServiceException;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.project.domain.YqgBarBills;
import com.ruoyi.project.domain.YqgConsumptionDetails;
import com.ruoyi.project.domain.YqgInformationProject;
import com.ruoyi.project.mapper.YqgBarBillsMapper;
import com.ruoyi.project.mapper.YqgConsumptionDetailsMapper;
import com.ruoyi.project.mapper.YqgInformationProjectMapper;
import com.ruoyi.project.module.zxm.tool.SchedulerTool;
import com.ruoyi.system.api.domain.SysUser;
import com.ruoyi.system.api.model.LoginUser;
import org.springframework.stereotype.Service;
import com.ruoyi.project.mapper.YqgInformationRoomMapper;
import com.ruoyi.project.domain.YqgInformationRoom;
import com.ruoyi.project.service.IYqgInformationRoomService;

import javax.annotation.Resource;

import static com.ruoyi.common.security.utils.SecurityUtils.getLoginUser;

/**
 * 房间基础信息Service业务层处理
 *
 * @author dr
 * @date 2023-04-17
 */
@Service
public class YqgInformationRoomServiceImpl implements IYqgInformationRoomService {
    @Resource
    private YqgInformationRoomMapper yqgInformationRoomMapper;
    @Resource
    private YqgInformationProjectMapper yqgInformationProjectMapper;
    @Resource
    private YqgBarBillsMapper yqgBarBillsMapper;
    @Resource
    private YqgConsumptionDetailsMapper yqgConsumptionDetailsMapper;
    @Resource
    private SchedulerTool schedulerTool;
    /**
     * 查询房间基础信息
     *
     * @param ID 房间基础信息主键
     * @return 房间基础信息
     */
    @Override
    public YqgInformationRoom selectYqgInformationRoomByID(Long ID) {
        return yqgInformationRoomMapper.selectYqgInformationRoomByID(ID);
    }

    /**
     * 查询房间基础信息列表
     *
     * @param yqgInformationRoom 房间基础信息
     * @return 房间基础信息
     */
    @Override
    public List<YqgInformationRoom> selectYqgInformationRoomList(YqgInformationRoom yqgInformationRoom) {
        return yqgInformationRoomMapper.selectYqgInformationRoomList(yqgInformationRoom);
    }

    /**
     * 新增房间基础信息
     *
     * @param yqgInformationRoom 房间基础信息
     * @return 结果
     */
    @Override
    public int insertYqgInformationRoom(YqgInformationRoom yqgInformationRoom) {
        return yqgInformationRoomMapper.insertYqgInformationRoom(yqgInformationRoom);
    }

    /**
     * 修改房间基础信息
     *
     * @param yqgInformationRoom 房间基础信息
     * @return 结果
     */
    @Override
    public int updateYqgInformationRoom(YqgInformationRoom yqgInformationRoom) {
        return yqgInformationRoomMapper.updateYqgInformationRoom(yqgInformationRoom);
    }

    /**
     * 批量删除房间基础信息
     *
     * @param IDs 需要删除的房间基础信息主键
     * @return 结果
     */
    @Override
    public int deleteYqgInformationRoomByIDs(Long[] IDs) {
        return yqgInformationRoomMapper.deleteYqgInformationRoomByIDs(IDs);
    }

    /**
     * 删除房间基础信息信息
     *
     * @param ID 房间基础信息主键
     * @return 结果
     */
    @Override
    public int deleteYqgInformationRoomByID(Long ID) {
        return yqgInformationRoomMapper.deleteYqgInformationRoomByID(ID);
    }


    @Override
    public int selectNormalCount() {
        List<YqgInformationRoom> result = yqgInformationRoomMapper.selectNormalCount();
        int size = result.size();
        return size;
    }

    @Override
    public List<YqgInformationRoom> selectByNoraml() {
        List<YqgInformationRoom> result = yqgInformationRoomMapper.selectNoralList();
        return result;
    }

    @Override
    public List<YqgInformationRoom> selectByNumber(String number) throws ParseException {
        List<YqgInformationRoom> result = yqgInformationRoomMapper.selectByNumber(number);
        //将同来去掉逗号
        YqgInformationProject yqgInformationProject = new YqgInformationProject();
        yqgInformationProject.setSecondaryClassification(result.get(0).getRoomType());
        yqgInformationProject.setEntryName(result.get(0).getRoomCharges());
        List<YqgInformationProject> a =
                yqgInformationProjectMapper.selectYqgInformationProjectList(yqgInformationProject);
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");



        YqgInformationProject temp = a.get(0);



        for (YqgInformationRoom yqgInformationRoom : result) {
            if (yqgInformationRoom.getInmate()!=null&&!yqgInformationRoom.getInmate().equals("")){

                yqgInformationRoom.setInmate(yqgInformationRoom.getInmate());
            }
            if (temp.getClockUpTime()!=null&&!temp.getClockUpTime().equals("")){
                yqgInformationRoom.setNote6("小时房");
                yqgInformationRoom.setNote5("开房"+temp.getClockUpTime()+"小时");
                //添加Calendar
                Calendar calendar = Calendar.getInstance();
                if (result.get(0).getNote1()!=null||!result.get(0).getNote1().equals("")){
                    Date open = dateFormat.parse(result.get(0).getNote1());
                    calendar.setTime(open);
                }


                Integer  time =  Integer.parseInt(temp.getClockUpTime());
                // 添加3个小时
                calendar.add(Calendar.HOUR_OF_DAY, time);
                // 获取添加后的时间
                Date newDate = calendar.getTime();
                String formattedDate = dateFormat.format(newDate);
                yqgInformationRoom.setNote4(formattedDate);
            }
            else {
                yqgInformationRoom.setNote6("全天房");
            }
        }



        return result;
    }

    @Override
    public List<YqgInformationRoom> selectByType(String roomType) {
        List<YqgInformationRoom> result = yqgInformationRoomMapper.selectByType(roomType);
        return result;
    }

    @Override
    //查询休息到时的房间号
    public List<YqgInformationRoom> selectLatterInforamtion() {
        ArrayList<YqgInformationRoom> yqgInformationRooms = new ArrayList<>();
        YqgInformationRoom yqgInformationRoom = new YqgInformationRoom();
//        LocalDateTime now = LocalDateTime.now();
//        long timestamp = now.toEpochSecond(ZoneOffset.UTC);
        Date date = new Date();
        List<YqgInformationRoom> result = yqgInformationRoomMapper.selectLatterInforamtion(yqgInformationRoom);

        List<YqgInformationRoom> collect = result.stream()
                .filter(a -> a.getCheckOutTime() != null && !a.getCheckOutTime().equals("")) // 不为null且不为空字符串
                .filter(a -> a.getCheckOutTime().before(date))
                .collect(Collectors.toList());
        return collect;
    }

    @Override
    public List<YqgInformationRoom> selectByClean() {
        YqgInformationRoom yqgInformationRoom = new YqgInformationRoom();
        List<YqgInformationRoom> result = yqgInformationRoomMapper.selectRoomListByClean(yqgInformationRoom);
        return result;
    }

    @Override
    public List<YqgInformationRoom> selectByWake() {


        List<YqgInformationRoom> result = yqgInformationRoomMapper.selectByWake();
        //System.out.println(result+"456");
        result = result.stream().filter(a -> a.getWakeUp() != null && !a.getWakeUp().equals("")).collect(Collectors.toList());
        //做一个定时任务，查询几点定时的
        return result;

    }

    @Override
    public int updateYqgInformationRoomByRoom(YqgInformationRoom yqgInformationRoom) {
        return   yqgInformationRoomMapper.updateByRoomByTime(yqgInformationRoom);

    }

    @Override
    public YqgInformationRoom selectByRoomNumber(String roomNumber) {
        YqgInformationRoom yqgInformationRoom =    yqgInformationRoomMapper.selectByRoomNumber(roomNumber);
        return yqgInformationRoom;
    }

    @Override
    public List<YqgInformationRoom> selectStatusCount() {
        List<YqgInformationRoom> result =   yqgInformationRoomMapper.selectStatusCount();
        ArrayList<YqgInformationRoom> yqgInformationRooms = new ArrayList<>();
        YqgInformationRoom yqgInformationRoom1 = new YqgInformationRoom();
        for (YqgInformationRoom yqgInformationRoom : result) {
            if (yqgInformationRoom.getRoomStatus().equals("0")){
                yqgInformationRoom1.setNote3(yqgInformationRoom.getNote7());
            }
            else if (yqgInformationRoom.getRoomStatus().equals("1")){
                yqgInformationRoom1.setNote4(yqgInformationRoom.getNote7());
            }
            else if (yqgInformationRoom.getRoomStatus().equals("2")){
                yqgInformationRoom1.setNote5(yqgInformationRoom.getNote7());
            }
            else if (yqgInformationRoom.getRoomStatus().equals("3")){
                yqgInformationRoom1.setNote6(yqgInformationRoom.getNote7());
            }
        }
        yqgInformationRooms.add(yqgInformationRoom1);
        //System.out.println(yqgInformationRooms+"9999");
        return yqgInformationRooms;
    }

    @Override
    public List<YqgInformationProject> selectJoin(String roomNumber) {


        //根据房间号查询房间类型
        YqgInformationRoom  result =   yqgInformationRoomMapper.selectByRoomNumber(roomNumber);

        if(result==null){
            throw new ServiceException("房间号输入错误");
        }
        String roomType = result.getRoomType();
        //根据房间类型查询项目表
        YqgInformationProject yqgInformationProject = new YqgInformationProject();
        yqgInformationProject.setSecondaryClassification(roomType);
        List<YqgInformationProject> infomation =
                yqgInformationProjectMapper.selectYqgInformationProjectList(yqgInformationProject);
        for (YqgInformationProject informationProject : infomation) {
            informationProject.setNote5(result.getRoomType());
        }
        return infomation;
    }


    //加钟
    @Override
    public YqgInformationRoom bellRoom(YqgInformationRoom yqgInformationRoom) throws ParseException {
        YqgInformationRoom result =   yqgInformationRoomMapper.selectByRoomNumber(yqgInformationRoom.getRoomNumber());
        if(!result.getRoomStatus().equals("1")){
            throw new ServiceException("此房间不能加钟");
        }
        YqgBarBills yqgBarBills = new YqgBarBills();
        yqgBarBills.setHandBrand(yqgInformationRoom.getHandBrand());
        yqgBarBills.setHandState("1");
        List<YqgBarBills> batailist = yqgBarBillsMapper.selectYqgBarBillsList(yqgBarBills);
        if(batailist.size()!=1){
            throw new ServiceException("此用户未开牌");
        }
        //查询是否有叫醒，有叫醒就做定时任务
        if (yqgInformationRoom.getWakeUp()!=null){
            schedulerTool.wakeupAt(yqgInformationRoom, yqgInformationRoom.getWakeUp());
        }


        //先将类型转换
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date open = dateFormat.parse(yqgInformationRoom.getNote1());
        //根据房间号查小时房加时时间
        YqgInformationProject yqgInformationProject = new YqgInformationProject();
        yqgInformationProject.setSecondaryClassification(yqgInformationRoom.getRoomType());
        yqgInformationProject.setEntryName(yqgInformationRoom.getRoomCharges());
        List<YqgInformationProject> a =
                yqgInformationProjectMapper.selectYqgInformationProjectList(yqgInformationProject);

        YqgInformationProject temp = a.get(0);
        if (temp.getClockUpTime()!=null&&!temp.getClockUpTime().equals("")){

            // 创建Calendar对象，并将时间设置为解析得到的时间
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(open);

            Integer  time =  Integer.parseInt(temp.getClockUpTime());

            // 添加3个小时
            calendar.add(Calendar.HOUR_OF_DAY, time);

            // 获取添加后的时间
            Date newDate = calendar.getTime();
            schedulerTool.latter(yqgInformationRoom, newDate);
            yqgInformationRoom.setCheckOutTime(newDate);

        }
        yqgInformationRoom.setRoomStatus("1");
        yqgInformationRoom.setOpeningHours(open);
        //根据房间类型查询项目表信息，然后插入到消费详细表



        yqgInformationRoomMapper.updateByRoom(yqgInformationRoom);

        extracted(yqgInformationRoom,a.get(0),batailist.get(0));
        return result;
    }

    //换全天房
    @Override
    public YqgInformationRoom fullRoom(YqgInformationRoom yqgInformationRoom) throws ParseException {
        YqgInformationRoom result =   yqgInformationRoomMapper.selectByRoomNumber(yqgInformationRoom.getRoomNumber());
        if(!result.getRoomStatus().equals("1")){
            throw new ServiceException("此房间不能换房");
        }
        YqgBarBills yqgBarBills = new YqgBarBills();
        yqgBarBills.setHandBrand(yqgInformationRoom.getHandBrand());
        yqgBarBills.setHandState("1");

        List<YqgBarBills> batailist = yqgBarBillsMapper.selectYqgBarBillsList(yqgBarBills);
        if(batailist.size()!=1){
            throw new ServiceException("此用户未开牌");
        }
        //查询是否有叫醒，有叫醒就做定时任务
        if (yqgInformationRoom.getWakeUp()!=null){
            schedulerTool.wakeupAt(yqgInformationRoom, yqgInformationRoom.getWakeUp());
        }
        //先将类型转换
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date open = dateFormat.parse(yqgInformationRoom.getNote1());
        //根据房间号查小时房加时时间
        YqgInformationProject yqgInformationProject = new YqgInformationProject();
        yqgInformationProject.setSecondaryClassification(yqgInformationRoom.getRoomType());
        yqgInformationProject.setEntryName(yqgInformationRoom.getRoomCharges());
        List<YqgInformationProject> a =
                yqgInformationProjectMapper.selectYqgInformationProjectList(yqgInformationProject);

        YqgInformationProject temp = a.get(0);
        if (temp.getClockUpTime()!=null&&!temp.getClockUpTime().equals("")){

            // 创建Calendar对象，并将时间设置为解析得到的时间
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(open);

            Integer  time =  Integer.parseInt(temp.getClockUpTime());
            // 添加3个小时
            calendar.add(Calendar.HOUR_OF_DAY, time);
            // 获取添加后的时间
            Date newDate = calendar.getTime();
            yqgInformationRoom.setCheckOutTime(newDate);
        }
        yqgInformationRoom.setRoomStatus("1");
        yqgInformationRoom.setOpeningHours(open);
        //根据房间类型查询项目表信息，然后插入到消费详细表
        yqgInformationRoomMapper.updateByRoom(yqgInformationRoom);
        //根据房间号和房间状态查询消费详细表，更新
        YqgConsumptionDetails yqgConsumptionDetails = new YqgConsumptionDetails();
        yqgConsumptionDetails.setSeat(yqgInformationRoom.getRoomNumber());
        yqgConsumptionDetails.setCheckOutStatus("1");
        List<YqgConsumptionDetails> yqgConsumptionDetails1 = yqgConsumptionDetailsMapper.selectYqgConsumptionDetailsList(yqgConsumptionDetails);
        //根据返回长度判断是否有加钟
             //如果没有，直接修改消费信息
        if (yqgConsumptionDetails1.size()==1){
            for (YqgConsumptionDetails consumptionDetails : yqgConsumptionDetails1) {
                consumptionDetails.setEntryName(yqgInformationRoom.getRoomCharges());
                consumptionDetails.setProjectCode(temp.getProjectCode());
                consumptionDetails.setProjectCategory(temp.getProjectCategory());
                consumptionDetails.setMnemonicCode(temp.getMnemonicCode());
                //添加单价
                consumptionDetails.setUnitPrice(temp.getUnitPrice());
                //添加金额
                consumptionDetails.setTotalAmount(temp.getUnitPrice());
                //添加提成
                consumptionDetails.setCommissionPrice(temp.getCommissionPrice());
                yqgConsumptionDetailsMapper.updateYqgConsumptionDetails(consumptionDetails);
            }
        }
        //如果有，会出现两条信息，然后都退单，再新增一条
        else {
            for (YqgConsumptionDetails consumptionDetails : yqgConsumptionDetails1) {
                consumptionDetails.setConsumptionStatus("1");
                consumptionDetails.setCheckOutStatus("2");
                yqgConsumptionDetailsMapper.updateYqgConsumptionDetails(consumptionDetails);
            }
            //新增一条
            extracted(yqgInformationRoom,a.get(0),batailist.get(0));
        }
        return result;
    }

    //在开房后进行的操作
    @Override
    public YqgInformationRoom startRoom(YqgInformationRoom yqgInformationRoom) throws ServiceException, ParseException {
        YqgInformationRoom result =   yqgInformationRoomMapper.selectByRoomNumber(yqgInformationRoom.getRoomNumber());
        if(!result.getRoomStatus().equals("0")){
            throw new ServiceException("此房间目前不能开房");
        }
        YqgBarBills yqgBarBills = new YqgBarBills();
        yqgBarBills.setHandBrand(yqgInformationRoom.getHandBrand());
        yqgBarBills.setHandState("1");
        List<YqgBarBills> batailist = yqgBarBillsMapper.selectYqgBarBillsList(yqgBarBills);
        //如果有同来，给同来也开一个消费记录
        if (yqgInformationRoom.getInmate()!=null){
            //对逗号进行切割
            String[] elements =  yqgInformationRoom.getInmate().split(",");
            for (String element : elements) {
                // 处理每个元素
                System.out.println(element+"hello");
                yqgBarBills.setHandBrand(element);
                // 账单表
                yqgBarBills.setHandState("1");
                List<YqgBarBills> batailist1 = yqgBarBillsMapper.selectYqgBarBillsList(yqgBarBills);
                //项目表
                YqgInformationProject yqgInformationProject = new YqgInformationProject();
                //开0元房费
                yqgInformationProject.setSecondaryClassification("002");
                yqgInformationProject.setEntryName("客房无房费0");
                List<YqgInformationProject> b =
                        yqgInformationProjectMapper.selectYqgInformationProjectList(yqgInformationProject);
                extracted(yqgInformationRoom,b.get(0),batailist1.get(0));
            }


        }


        if(batailist.size()!=1){
            throw new ServiceException("此用户未开牌");
        }
        //查询是否有叫醒，有叫醒就做定时任务
        if (yqgInformationRoom.getWakeUp()!=null){
            schedulerTool.wakeupAt(yqgInformationRoom, yqgInformationRoom.getWakeUp());
        }

        //先将类型转换
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date open = dateFormat.parse(yqgInformationRoom.getNote1());
        //根据房间号查小时房加时时间
        YqgInformationProject yqgInformationProject = new YqgInformationProject();
        yqgInformationProject.setSecondaryClassification(yqgInformationRoom.getRoomType());
        yqgInformationProject.setEntryName(yqgInformationRoom.getRoomCharges());


        //查询正常开牌的
        List<YqgInformationProject> a =
                yqgInformationProjectMapper.selectYqgInformationProjectList(yqgInformationProject);

        YqgInformationProject temp = a.get(0);
        if (temp.getClockUpTime()!=null&&!temp.getClockUpTime().equals("")){

            // 创建Calendar对象，并将时间设置为解析得到的时间
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(open);

           Integer  time =  Integer.parseInt(temp.getClockUpTime());




            // 客房表添加3个小时
            calendar.add(Calendar.HOUR_OF_DAY, time);

            // 获取添加后的时间
            Date newDate = calendar.getTime();

            //如果开的小时房，也做定时任务

            schedulerTool.latter(yqgInformationRoom, newDate);
            System.out.println(newDate+"woshi");
            yqgInformationRoom.setCheckOutTime(newDate);

        }
        yqgInformationRoom.setRoomStatus("1");
        yqgInformationRoom.setOpeningHours(open);
        //根据房间类型查询项目表信息，然后插入到消费详细表



        yqgInformationRoomMapper.updateByRoom(yqgInformationRoom);

        extracted(yqgInformationRoom,a.get(0),batailist.get(0));
        return result;
    }



    private void extracted(YqgInformationRoom yqgInformationRoom,YqgInformationProject yqgInformationProject,
                           YqgBarBills yqgBarBills) {
        YqgConsumptionDetails yqgConsumptionDetails = new YqgConsumptionDetails();

        /**
         * 添加用户信息
         */
        LoginUser loginUser = getLoginUser();
        SysUser user = loginUser.getSysUser();

        //添加用户id
        yqgConsumptionDetails.setUserId(user.getUserId());
        //添加用户姓名
        yqgConsumptionDetails.setUserName(user.getUserName());
        //添加用户部门
        yqgConsumptionDetails.setDeptId(user.getDeptId());
        //添加昵称
        yqgConsumptionDetails.setNickName(user.getNickName());
        //添加手牌号
        yqgConsumptionDetails.setHandBrand(yqgInformationRoom.getHandBrand());


        //添加手牌状态
        yqgConsumptionDetails.setHandState("1");



        /**
         * 添加项目信息
         */
        //添加项目名称
        yqgConsumptionDetails.setEntryName(yqgInformationProject.getEntryName());
        //添加项目类别
        yqgConsumptionDetails.setProjectCategory(yqgInformationProject.getProjectCategory());
        //添加项目代码
        yqgConsumptionDetails.setMnemonicCode(yqgInformationProject.getMnemonicCode());
        //添加代码
        yqgConsumptionDetails.setProjectCode(yqgInformationProject.getProjectCode());
        //添加单位
        yqgConsumptionDetails.setUnit(yqgInformationProject.getUnit());

        //添加单价
        yqgConsumptionDetails.setUnitPrice(yqgInformationProject.getUnitPrice());

        //添加金额
        yqgConsumptionDetails.setTotalAmount(yqgInformationProject.getUnitPrice());
        //添加提成
        yqgConsumptionDetails.setCommissionPrice(yqgInformationProject.getCommissionPrice());

        /**
         * 账单信息
         */
        //添加账单id
        yqgConsumptionDetails.setBarBillsId(yqgBarBills.getID());
        //添加留牌状态
        yqgConsumptionDetails.setRetentionStatus(yqgBarBills.getRetentionStatus());
        //添加并牌状态
        yqgConsumptionDetails.setMergeStatus(yqgBarBills.getMergeStatus());
        //添加同来
        yqgConsumptionDetails.setTogether(yqgBarBills.getTogether());
        //添加到店时间
        yqgConsumptionDetails.setOpeningTime(DateUtils.getNowDate());
        //添加手牌类别
        yqgConsumptionDetails.setHandCategory(yqgBarBills.getHandCategory());
        //原手牌
        yqgConsumptionDetails.setOriginalHand(yqgBarBills.getOriginalHand());
        //交班状态
        yqgConsumptionDetails.setHandoverStatus(yqgBarBills.getHandoverStatus());

        /**
         * 消费信息
         */

        //添加录单时间
        yqgConsumptionDetails.setRecordingTime(yqgInformationRoom.getOpeningHours());
        //添加数量
        yqgConsumptionDetails.setQuantity("1");

        //添加位置
        yqgConsumptionDetails.setSeat(yqgInformationRoom.getRoomNumber());

        //添加消费状态
        yqgConsumptionDetails.setConsumptionStatus("0");

        /**
         *  添加客房信息
         */

        //添加房间类型
        yqgConsumptionDetails.setRoomType(yqgInformationRoom.getRoomType());
        //添加开房时间
        yqgConsumptionDetails.setOpeningHours(yqgInformationRoom.getOpeningHours());
        //添加退房时间
        // yqgConsumptionDetails.setCheckOutTime(yqgConsumptionDetails.getCheckOutTime());
        //添加退房状态
        //添加到备注字段（房间号信息）
        yqgConsumptionDetails.setNote10("房间号"+yqgInformationRoom.getRoomNumber());
        yqgConsumptionDetails.setCheckOutStatus(yqgInformationRoom.getRoomStatus());
        yqgConsumptionDetailsMapper.insertYqgConsumptionDetails(yqgConsumptionDetails);
    }
}
